package com.echo.fm.content.activity;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.echo.fm.content.activity.model.Action;
import com.echo.fm.content.activity.model.ActionItem;
import com.echo.util.ErrorException;
import com.echo.util.ResultUtils;
import com.echo.util.impl.ValidateUtils;

@Repository("actionPersistence")
public class DaoActionPersistenceImpl implements IActionPersistence {
	@Autowired
	@Qualifier("sessionFactory")
	SessionFactory sessionFactory;

	public int insertAction(Action action, List<ActionItem> itemList) throws ErrorException {
		Session session = null;
		Transaction tx = null;

		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			Integer actionId = (Integer) session.save(action);
			for (ActionItem actionItem : itemList) {
				actionItem.setActionId(actionId);
				session.save(actionItem);
			}
			tx.commit();
			return actionId;
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	public void updateAction(Action action) throws ErrorException {
		Session session = null;
		Transaction tx = null;
		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			session.update(action);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	public void updateAction(Action action, List<ActionItem> itemList) throws ErrorException {
		Session session = null;
		Transaction tx = null;
		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			List<ActionItem> existActionItem = searchActionItemList(action.getActionId());
			if (existActionItem != null) {
				for (ActionItem actionItem : existActionItem) {
					session.delete(actionItem);
				}
			}
			session.update(action);
			if (itemList != null) {
				for (ActionItem actionItem : itemList) {
					session.save(actionItem);
				}
			}
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null) {
				session.close();
			}
		}

	}

	public void deleteAction(Action action) throws ErrorException {
		Session session = null;
		Transaction tx = null;
		try {
			session = sessionFactory.openSession();
			tx = session.beginTransaction();
			session.delete(action);
			tx.commit();
		} catch (HibernateException e) {
			tx.rollback();
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	public Action searchActionById(int id) throws ErrorException {
		Session session = null;
		try {
			session = sessionFactory.openSession();
			return (Action) session.get(Action.class, id);
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	public List<ActionItem> searchActionItemList(int actionId) throws ErrorException {

		Session session = null;
		try {
			session = sessionFactory.openSession();
			@SuppressWarnings("unchecked")
			List<ActionItem> actionItems = session.createQuery("from ActionItem where actionId=:actionId")
					.setInteger("actionId", actionId).list();
			return actionItems;
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	public Long searchActionListCount(String title, Integer actionType, Integer status, Long searchStartTime,
			Long searchFinalTime, Integer loopStatus) throws ErrorException {
		Session session = null;
		try {
			session = sessionFactory.openSession();
			StringBuffer stringBuffer = new StringBuffer();
			String query = "select count(*) from Action where 1=1";
			stringBuffer.append(query);
			if (ValidateUtils.isNotEmpty(title)) {
				String titleQuery = "and title like '%" + title + "%'";
				stringBuffer.append(titleQuery);
			}
			if (actionType != null) {
				String actionTypeQuery = "and actionType = %d";
				stringBuffer.append(String.format(actionTypeQuery, actionType));
			}
			if (status != null) {
				String statusQuery = "and status = %d";
				stringBuffer.append(String.format(statusQuery, status));
			}
			if ((searchStartTime != null && searchStartTime != 0L)
					&& (searchFinalTime != null && searchFinalTime != 0L)) {
				String dateQuery = "and cdate between %d and %d";
				stringBuffer.append(String.format(dateQuery, searchStartTime, searchFinalTime));

			}
			if (loopStatus != null) {
				String loopStatusQuery = "and loopStatus = %d";
				stringBuffer.append(String.format(loopStatusQuery, loopStatus));
			}
			Long result = (Long) session.createQuery(stringBuffer.toString()).uniqueResult();
			return result;
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	public List<Action> searchActionList(String title, Integer actionType, Integer status, Long searchStartTime,
			Long searchFinalTime, Integer loopStatus, Integer firstResult, Integer maxResults) throws ErrorException {

		Session session = null;
		try {
			session = sessionFactory.openSession();
			StringBuffer stringBuffer = new StringBuffer();
			String query = "from Action where 1=1";
			stringBuffer.append(query);
			if (title != null) {
				String titleQuery = "and title like'%" + title + "%'";
				stringBuffer.append(titleQuery);
			}
			if (actionType != null) {
				String actionTypeQuery = "and actionType = %d";
				stringBuffer.append(String.format(actionTypeQuery, actionType));
			}
			if (status != null) {
				String statusQuery = "and status = %d";
				stringBuffer.append(String.format(statusQuery, status));
			}
			if ((searchStartTime != null && searchStartTime != 0L)
					&& (searchFinalTime != null && searchFinalTime != 0L)) {
				String dateQuery = "and cdate between %d and %d";
				stringBuffer.append(String.format(dateQuery, searchStartTime, searchFinalTime));

			}
			if (loopStatus != null) {
				String loopStatusQuery = "and loopStatus = %d";
				stringBuffer.append(String.format(loopStatusQuery, loopStatus));
			}
			@SuppressWarnings("unchecked")
			List<Action> actionList = (List<Action>) session.createQuery(stringBuffer.toString())
					.setMaxResults(maxResults).list();
			return actionList;
		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

	@Test
	public void test() {

		Session session = null;
		try {
			session = sessionFactory.openSession();
			// Iterator iterator = session.createQuery("from Action where
			// id<18").iterate();
			// while (iterator.hasNext()) {
			// Action action = (Action) iterator.next();
			// System.out.println(action.getTitle());
			// }
			// System.out.println("---------------");
			//
			//
			//
			// while (iterator.hasNext()) {
			// Action action = (Action) iterator.next();
			// System.out.println(action.getTitle());
			// }
			// iterator = session.createQuery("from Action a where
			// a.id<18").iterate();
			// while (iterator.hasNext()) {
			// Action student = (Action) iterator.next();
			// System.out.println(student.getTitle());
			//
			// }
			// iterator = session.createQuery("from Action a where
			// a.id<17").iterate();
			//
			// while (iterator.hasNext()) {
			// Action teacher = (Action ) iterator.next();
			// System.out.println(teacher.getTitle());
			// }

			List<Action> actionList = session.createQuery("FROM Action where id<17").list();
			for (Action action : actionList) {
				System.out.println(action.getTitle());
			}
			System.out.println("--------------------------------------");
			List<Action> actionList2 = session.createQuery("FROM Action where id<17").list();
			for (Action action : actionList2) {
				System.out.println(action.getTitle());
			}

			// List<Action> actionList3 =session.createQuery("from Action where
			// id<18").list();
			// for (Action action : actionList3) {
			// System.out.println(action.getTitle());
			//
			// }

		} catch (HibernateException e) {
			e.printStackTrace();
		}

	}

	public List<Action> searchActionList() throws ErrorException {

		Session session = null;
		try {
			session = sessionFactory.openSession();
			List<Action> actions = (List<Action>) session.createQuery("from Action where 1=1").list();
			return actions;

		} catch (HibernateException e) {
			e.printStackTrace();
			throw new ErrorException(ResultUtils.WEB_DB_SERVER_ERROR_CODE);
		} finally {
			if (session != null)
				session.close();
		}

	}

}
